
import axios, { AxiosError } from 'axios'
import storage from './storage'
import { message } from './AntdGlobal'
// 导入等待框
import { showLoading, hideLoading } from './loading/index'

import configRequest from '@/config/index';

// 创建实例
const instance = axios.create({
    baseURL: configRequest.baseApi,
    timeout: 80000,//超时时间 8秒
    timeoutErrorMessage: "请求超时时，请稍后重试",
    headers: {
        // icode: '4C9A49C226B59CD8'
    },
    withCredentials: true // 跨域请求时发送 cookies
});
// 请求拦截器
instance.interceptors.request.use(
    config => {
        if(config.showError){
            showLoading();
        }
        const token = storage.get('token')
        if (token) {
            config.headers.Authorization = 'Bearer ' + token
        }
        return {
            ...config
        }
    },
    (error: AxiosError) => {
        return Promise.reject(error)
    }
)

// 响应拦截器
instance.interceptors.response.use(
    response => {
        hideLoading();
        const data = response.data;
        if (response.config.responseType === 'blob') return response
        if (data.code === 500001) {
            message.error(data.msg)
            storage.remove('token')
            location.href = '/login?callback=' + encodeURIComponent(location.href)
        } else if (data.code != 0) {
            if (response.config.showError === false) {
                return Promise.resolve(data)
            } else {
                message.error(data.msg)
                return Promise.reject(data)
            }
        }
        return data.data
    },
    error => {
        hideLoading();
        message.error(error.message)
        return Promise.reject(error.message)
    }
)


interface Iconfig {
    showLoading: boolean;
    showError: boolean;
}
export default {
    get<T>(url: string, params?: object, options: Iconfig = { showError: true, showLoading: true }): Promise<T> {
        return instance.get(url, { params, ...options });
    },
    post<T>(url: string, params?: object, options: Iconfig = { showLoading: true, showError: true }): Promise<T> {
        return instance.post(url, params, options)
    }
}

